<template>
  <div>
    <!-- 添加界面 -->
    <el-button 
      type="primary" 
      @click="addStudent" 
      color="#FFB805"
      :disabled="!this.hasAuth('sys:student:add')"
      >添加</el-button>
    <el-dialog v-model="dialogFormToAdd" title="添加信息">
      <el-form
      ref="InfoForm"
      :rules="rules"
      :model="InfoForm"
      label-width="100px"
      class="demo-ruleForm"
      enctype="multipart/form-data"
      action="" method="post"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="InfoForm.name" type="text"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="InfoForm.age" type="text"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-input type="file" v-model="file" multiple="multiple"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('InfoForm')">Submit</el-button>
          <el-button @click="resetForm('InfoForm')">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../../utils/request'
import { ElMessage } from 'element-plus'
export default {
  name: "add",
  props:["isOpen"],
  inject: ['reload'],  
  data(){
    return{
      InfoForm: {
            id:'',
            name: '',
            age: ''},
      file:null,
      dialogFormToAdd:this.isOpen,
      // 表单校验规则
      rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          age: [
            { required: true, message: '请输入年龄', trigger: 'blur' }
          ],      
      }
    }
    },
    methods:{
      addStudent(){
        this.dialogFormToAdd = true;
      },
      //表单提交
      submitForm(formName){
        this.$refs[formName].validate((valid) => {
          if(valid){
            console.log(this.file)
            var formData = new window.FormData();
            formData.append("student", new Blob([JSON.stringify(this.InfoForm)],{type: "application/json"}));
          formData.append('file',this.file);
            axios.post("/students/add",formData)
            // axios({
            //   url:'/students/add',
            //   method:'post',
            //   data:formData,
            //   cache:false,
            //   processData:false,
            //   contentType:false,
            // })
            .then(res=>{
                ElMessage({
                  message: res.data.message,
                  type: 'success',
                })
              this.reload()
            })
            
          }else{
            console.log("提交数据失败")
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
    },
    hasAuth(perm){
            var authority = this.$store.state.menus.permList;
            return authority.indexOf(perm) > -1;
        }
  }
}
</script>
